/*
 * Copyright (c) 2025 EasyAdmin
 * All rights reserved.
 *
 * This file is part of the [EasAdmin] project.
 * Unauthorized copying of this file, via any medium, is strictly prohibited.
 * Proprietary and confidential.
 *
 * Author: EasyAdmin ( 1073602@qq.com )
 * Website: https://www.xhxiao.com
 */
package com.easy.module.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easy.framework.common.utils.Func;
import com.easy.module.system.entity.SysAppMenu;
import com.easy.module.system.mapper.SysAppMenuMapper;
import com.easy.module.system.service.ISysAppMenuAuthService;
import com.easy.module.system.service.ISysAppMenuService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 应用菜单 Service业务
 *
 * @author EasyAdmin ( 1073602@qq.com )
 * @date 2025-08-20
 */
@RequiredArgsConstructor
@Service
public class SysAppMenuServiceImpl extends ServiceImpl<SysAppMenuMapper , SysAppMenu> implements ISysAppMenuService
{

    final ISysAppMenuAuthService sysAppMenuAuthService;

    /**
     * @param orgId
     * @param roleIdList
     * @param userId
     * @return
     */
    @Override
    public List<SysAppMenu> menuTree(Long orgId, List<Long> roleIdList, Long userId) {
        //登录用户相关授权菜单
        List<Long> menuIdList = sysAppMenuAuthService.getMenuIdListByOrgId(orgId, roleIdList, userId);
        List<SysAppMenu> list = list(lambdaQueryWrapper().in(Func.isNotEmpty(menuIdList),SysAppMenu::getId, menuIdList));
        List<SysAppMenu> menuTreeList = childPerms(list, 0L);
        return menuTreeList;
    }

    /**
     * 根据父节点的ID获取所有子节点
     */
    @Override
    public List<SysAppMenu> childPerms(List<SysAppMenu> list, Long parentId) {
        List<SysAppMenu> functionItemTrees = new ArrayList<>();
        if (Func.isNotEmpty(list)) {
            for (SysAppMenu functionItem : list) {
                if (functionItem.getParentId().equals(parentId)) {
                    functionItem.setChildren(recursion(list, functionItem));
                    functionItemTrees.add(functionItem);
                }
            }
        }
        return functionItemTrees;
    }

    private List<SysAppMenu> recursion(List<SysAppMenu> list, SysAppMenu parent) {
        List<SysAppMenu> result = Lists.newArrayList();
        for (SysAppMenu functionItem : list) {
            if (functionItem.getParentId().equals(parent.getId())) {
                functionItem.setChildren(recursion(list, functionItem));
                result.add(functionItem);
            }
        }
        return result;
    }

}